import React, { Component } from 'react'
import { StyleSheet, Text } from 'react-native'
import { ScaleS, ScaleT, ONE_PIXEL } from 'src/utils/ScreenUtil'
import PropTypes from 'prop-types'
import CustomButton from '../button/CustomButton'

export default class CheckTag extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isActive: props.isActive,
      switchType: props.switchType
    }
  }

  UNSAFE_componentWillReceiveProps (nexProps) {
    if (this.state.isActive !== nexProps.isActive) {
      this.setState({
        isActive: nexProps.isActive
      })
    }
  }

  render () {
    const { tagLabel, style, activeBgColor, bgColor, params } = this.props
    const { isActive } = this.state
    return tagLabel ? (
      <CustomButton
        style={[styles.tagView, { backgroundColor: isActive ? activeBgColor : bgColor }].concat(style)}
        onPress={this._onPress}
        params={params}>
        <Text style={[styles.tagText, { fontWeight: isActive ? '500' : '400' }]}>{tagLabel}</Text>
      </CustomButton>
    ) : null
  }

  _onPress = (params) => {
    const { switchType } = this.props
    const { isActive } = this.state
    const active = !isActive
    switch (switchType) {
      case 'toggle':
        this._setActive(active, params)
        break
      case 'open':
        active && this._setActive(active, params)
        break
      case 'close':
        !active && this._setActive(active, params)
        break
    }
  }

  _setActive = (active, params) => {
    const { onPress } = this.props
    this.setState({
      isActive: active
    }, () => {
      onPress && onPress(active, params)
    })
  }
}
CheckTag.propTypes = {
  tagLabel: PropTypes.string,
  activeBgColor: PropTypes.string,
  bgColor: PropTypes.string,
  isActive: PropTypes.bool,
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  onPress: PropTypes.func,
  params: PropTypes.object,
  switchType: PropTypes.string
}
CheckTag.defaultProps = {
  activeBgColor: '#FFE400',
  bgColor: 'transparent'
}

const styles = StyleSheet.create({
  tagView: {
    width: ScaleS(100),
    height: ScaleS(39),
    borderRadius: ScaleS(20),
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: '#ECECEC',
    borderWidth: ONE_PIXEL,
    borderStyle: 'solid'
  },
  tagText: {
    color: '#3C3C3C',
    fontSize: ScaleT(14),
    fontWeight: '400'
  }
})
